using AutojsController.Helpers;
using AutojsController.ViewModels;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.VisualTree;
using System.ComponentModel;
using System.Linq;

namespace AutojsController.Views;

public partial class MobileView : UserControl
{
    public MobileView()
    {
        InitializeComponent();
    }

    protected override void OnPointerPressed(PointerPressedEventArgs e)
    {
        base.OnPointerPressed(e);

        var point = e.GetCurrentPoint(this);
        if (point.Properties.IsRightButtonPressed)
        {
            var hitTest = this.InputHitTest(point.Position);
            var current = hitTest as Visual;

            while (current != null)
            {
                if (current is MobileItemView mobileItemView &&
                    mobileItemView.DataContext is MobileItemViewModel mobileItemViewModel)
                {
                    mobileItemViewModel.IsSelected = true;
                    break;
                }
                current = current.GetVisualParent();
            }

            if (this.DataContext is MobileViewModel mobvm && mobvm.Mobiles.Any(m => m.IsSelected))
            {
                DeleteMenuItem.IsVisible = true;
                OperationsItem.IsVisible = true;
            }
            else
            {
                DeleteMenuItem.IsVisible = false;
                OperationsItem.IsVisible = false;
            }
        }
        //TODO: 通过计算所有选中项的状态来继续调整子菜单是否可用
    }

    //使用ContextMenu的Opening事件来动态调整菜单不可行
    private void MobileActionMenus_Opening(object sender, CancelEventArgs e)
    {
        //var contextMenu = sender as ContextMenu;
        //Debug.WriteLine($"ContextMenu Opening, placementTarget is {contextMenu?.PlacementTarget}");
        //通过Cluade寻问,有可能是Bug,在从MobileItemView上右键时,事件冒泡到这里PlacementTarget会变成null
        //改为通过鼠标坐标获取
    }
}